package com.selangshiwo.sina.requst;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;

import com.selangshiwo.Util;

public class RequestPack implements IRequestPack {
	
	private String strUrl = "";
	private Map<String , String> params = new HashMap<String , String>();
	private HttpRequestBase httpMethod = null ;
	private String type = "get";
	
	/**
	 * 	默认创建httpGet
	 */
	public RequestPack(){
		httpMethod = new HttpGet();
	}
	
	
	public RequestPack(String type){
		if("post".equals(type.toLowerCase())){
			this.type = "post";
			httpMethod = new HttpPost();
		}else{
			httpMethod = new HttpGet();
		}
		
	}
	
	/**
	 * 
	 * 
	 * @param type		因暂时只有get和post，不做枚举
	 * @param url
	 */
	public RequestPack(String type , String url){
		this.strUrl = url ;
		if("post".equals(type.toLowerCase())){
			this.type = "post";
			httpMethod = new HttpPost(url);
		}else if("get".equals(type.toLowerCase())){
			httpMethod = new HttpGet(url);
		}else{
			httpMethod = null ;
		}
	}
	
	@Override
	public void setHeader(String key, String val) {
		httpMethod.setHeader(key , val);
	}

	@Override
	public void setParam(String key, String val) {
		params.put( key, val );
	}
	
	@Override
	public HttpRequestBase getHttpMethod() throws URISyntaxException {
		//加入头和参数
		setDefaultParams() ;
//		
//		if(this.httpMethod != null)
//			return this.httpMethod ;
		
		if("".equals(this.strUrl))
			throw new NullPointerException("请求地址不存在!");

		URIBuilder uri = new URIBuilder();
		
		uri = uri.setScheme(Util.getUrlScheme(strUrl)).setHost(Util.getUrlHost(strUrl))
			.setPath(Util.getUrlPath(strUrl));
		
		//因为绑定URIBuilder，所以不单独实现
		String strUrlParams = Util.getUrlParams(strUrl) ;
		if("".equals(strUrlParams) == false){
			String[] aryParam = strUrlParams.split("&");
			for(int len = aryParam.length - 1 ; len >= 0 ; len --){
				//坑比的只取第一个等号
				String[] ps = aryParam[len].split("=",2);
				this.setParam(ps[0], ps[1]);
			}
		}
		
		
		//根据请求类型处理请求包
		Iterator<String> it = this.params.keySet().iterator() ;

		if("get".equals(this.type)){
			while(it.hasNext()){
				String key = it.next() ;
				String val = this.params.get(key);
				uri.setParameter(key, val) ;
			}
		}else{
			//post
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			while(it.hasNext()){
				String key = it.next() ;
				String val = this.params.get(key) ;
				nvps.add(new BasicNameValuePair(key , val));
			}
			((HttpPost)this.httpMethod).setEntity(new UrlEncodedFormEntity(nvps , Consts.UTF_8));
		}
		
		this.httpMethod.setURI(uri.build());
		
		dumpHttpRequestInfo();	//log
		
		return this.httpMethod ;
	}

	@Override
	public void setUrl(String url) {
			this.strUrl = url ;
	}

	private void dumpHttpRequestInfo(){
		
		Util.debug("请求URL ： " + this.httpMethod.getURI());
		Util.debug("请求类型：" + this.type );
		String strParamsLog = "请求参数：";
		Iterator<String> it = this.params.keySet().iterator() ;
		while(it.hasNext()){
			String key = it.next() ;
			String val = this.params.get(key);
			strParamsLog += "\n[" + key + "=" + val + "],";
		}
		Util.debug(strParamsLog);
	}
	
	@Override
	public String getType() {
		return this.type ;
	}


	@Override
	public void setDefaultParams() {
		
	}

	public HttpRequestBase getMethod(){
		return this.httpMethod ;
	}
	
}